<template>
    <div id="getDataBySql">
        <el-form
            :model="formData"
            ref="form"
        >
            <el-tabs type ='border-card' v-model="activeName" @tab-click="handleClick">
                <el-tab-pane  label="数据导入--SQL导入" name="first">
                    <el-container>
                        <el-header style="margin-top: -10px;height: 45px;border: 1px solid #f5f7fa;">
                            <el-row>
                                <el-form-item label="数据来自数据连接:"
                                              style="width: 100%"
                                              prop="conDataInfo">
                                    <el-select  size ='mini' v-model="formData.connId" placeholder="请选择">
                                        <el-option
                                            v-for="item in linkData"
                                            :key="item.connId"
                                            :label="item.name"
                                            :value="item.connId">
                                        </el-option>
                                    </el-select>
                                    <el-button
                                     style="background-color:#f04959;height: 35px;margin-left: 600px;margin-top: 2px;color:white ;"
                                               @click="okBtnClicked()">确认</el-button>
                                    <el-button @click="cancel"
                                        style="background-color:white;height: 35px;margin-left: 10px;margin-top: 2px;color: #f04959;"
                                    >取消</el-button>
                                </el-form-item>

                            </el-row>
                        </el-header>
                    </el-container>
                    <el-container>
                        <el-aside style="width: 430px;">
                            <div height="455px" >
                                <div style="margin-top: 10px">
                                </div>
                                <div style="width: 430px;margin-top: 1px">
                                    <span>SQL语句</span>
                                    <el-form-item prop="sql">
                                        <el-input
                                            type="textarea"
                                            :rows="7"
                                            placeholder="请输入内容"
                                            v-model="formData.sql">
                                        </el-input>
                                    </el-form-item>
                                </div>
                            </div>
                                <div>
                                    <span>参数设置</span>
                                    <el-button @click="getParams()" icon="el-icon-refresh-left"
                                               style="background-color:#f04959;height: 35px;margin-left: 220px;color: white;">刷新
                                    </el-button>
                                    <el-container>
                                            <el-mian>
                                                <el-form-item>
                                                    <el-table
                                                        :data="paramData"
                                                        height="210px"
                                                        :row-style="{height: '35px',border: 'none',}"
                                                        :cell-style="{padding: '0'}"
                                                        style="width: 430px;border: 1px solid rgba(153,153,153,0.28);">
                                                        <el-table-column  prop="param" label="参数名" min-width="20%" v-model="formData.param"></el-table-column>
                                                        <el-table-column prop="type" label="参数类型" min-width="35%" >
                                                            <template slot-scope="scope">
                                                                <el-select size="mini" v-model="scope.row.type" placeholder="请选择" @change="handleEvents">
                                                                    <el-option
                                                                        v-for="item in options"
                                                                        :key="item.value"
                                                                        :label="item.label"
                                                                        :value="item.value">
                                                                    </el-option>
                                                                </el-select>
                                                            </template>
                                                        </el-table-column>
                                                        <el-table-column prop="input" label="值" min-width="40%">
                                                            <template slot-scope="scope">
                                                                <el-input size="mini" v-if="scope.row.type!='2'" v-model="scope.row.input"></el-input>
                                                                <el-date-picker v-if="scope.row.type==='2'"
                                                                                v-model="scope.row.input"
                                                                                type="date"
                                                                                placeholder="选择日期">
                                                                </el-date-picker>
                                                            </template>
                                                        </el-table-column>
                                                    </el-table>
                                                </el-form-item>
                                            </el-mian>
                                    </el-container>
                                </div>
                        </el-aside>
                        <el-main style="margin-top: -22px;">
                            <div style="margin-top: 10px;border: 1px solid rgba(153,153,153,0.28);background-color: white">
                                <div style="border-bottom: 1px solid rgba(153,153,153,0.28);display: flex;height: 50px;line-height: 50px">
                                   <div style="margin-left: 10px;font-weight: bold" >数据预览</div>
                                   <el-button style="background-color:#f04959;height: 35px;margin-left: 480px;margin-top:5px;color: white;" @click="getTableData">预览</el-button>
                                </div>
                                <el-form-item style="width: 690px">
                                    <ATable v-if="isShowTable"
                                        :tableData ="tableData"
                                        :height="height"
                                        :recordNumber="recordNumber"
                                        @getData ='getTableData'></ATable>
                                    <!--<data-table-com v-if="isShowTable"  :height="height" :tableData="tableData" @getData="getTableData"></data-table-com>-->
                                </el-form-item>
                            </div>
                        </el-main>
                    </el-container>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </div>
</template>

<script>
    import {
        DATABASE_CON_SAVE, GET_DATAINFO, QUERY_DBLINK, QUERY_TMP_DATA_TABLE, CUST_SQL_MAINTAIN, DATA_PARAM_QUERY
    } from '@api/url'
    import ajax from '@api/ajax'
    import dataTableCom from './DataTableCom'
    import addMenuEvents from '@/components/group/addEvent.js' // 新增菜单

    export default {
        name: 'GetDataBySql',
        data () {
            return {
                formData: {
                    sql: '',
                    connId: ''
                },
                activeIndex: '1',
                treeData: null,
                isShowTable: true,
                isShowSelfData: false,
                height: window.innerHeight - 250,
                elevanceView: false,
                selectType: '1', // 选中的表类型 1：数据预览 2血缘分析 3关联视图
                tableTitle: '表格标题',
                menuData: {}, // 选中的数据,
                editFlag: false, // 是否是编辑模式
                tableData: [],
                paramData: [], // 存储参数数组
                options: [{
                    value: '1',
                    label: '文本'
                }, {
                    value: '2',
                    label: '日期'
                }, {
                    value: '3',
                    label: '数值'
                }],
                value: '',
                linkData: [],
                activeName: 'first',
                recordNumber: 0,
                editData: {}
            }
        },
        methods: {
            handleEvents (val) {
                debugger
                this.$forceUpdate()
            },
            getDbLink () {
                let Conditions = {}
                Conditions.connType = 'I'
                ajax.post(QUERY_DBLINK, Conditions).then(res => {
                  this.linkData = res.data.records
                }).catch(err => {

                })
            },
            async okBtnClicked () {
                // 查询table数据
                let optMode
                if (this.editFlag) {
                    optMode = 'U'
                } else {
                    optMode = 'A'
                    debugger
                    await addMenuEvents.addEvent(this)
                }

                let Conditions = {
                    modelId: optMode === 'U' ? this.editData.menuId : this.$storeSave.state.addelevanceObj.menuId,
                    tableId: optMode === 'U' ? this.editData.menuId : this.$storeSave.state.addelevanceObj.menuId,
                    optMode: optMode, // 操作类型
                    connId: this.formData.connId, // 连接Id
                    modelName: optMode === 'U' ? this.editData.name : this.$storeSave.state.addelevanceObj.name, // 表名
                    pcWhere: this.formData.sql, // sql语句
                    modelType: '1',
                    pcGrp: '',
                    pcOrder: '',
                    flag: '0',
                    type: this.value, // 参数值的类型
                    tdpps: [],
                    createdBy: 'lzy',
                    createdDt: '20210118',
                    updatedBy: 'lzy',
                    updatedDt: '20200118'

                }
                debugger
                for (let i in this.paramData) {
                    let param = {
                        modelId: optMode === 'U' ? this.editData.menuId : this.$storeSave.state.addelevanceObj.menuId,
                        paramName: '${' + this.paramData[i].param + '}',
                        paramType: this.paramData[i].type,
                        defaultVal: this.paramData[i].input,
                        createdBy: 'lzy',
                        createdDt: '20210118',
                        updatedBy: 'lzy',
                        updatedDt: '20200118'
                    }
                    Conditions.tdpps.push(param)
                }
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        ajax.post(CUST_SQL_MAINTAIN, Conditions).then(res => {
                            this.clearStageData()
                            this.$emit('showSelfData')
                            this.$message.success('保存成功！')
                        }).catch(err => {
                            console.error('保存失败！', err)
                        })
                    } else {
                        return false
                    }
                })
            },
            clearStageData () {
                this.formData = {}
                this.$refs.form.clearValidate()
            },
            getTableData (data) {
                var vm = this
                let Conditions = {
                    connId: this.formData.connId,
                    tdpps: []
                }
                if (data != null && data.pageNo != null && data != undefined) {
                    Conditions.pageNo = data.pageNo,
                    Conditions.pageSize = data.pageSize
                } else {
                    Conditions.pageNo = '1'
                    Conditions.pageSize = '15'
                }
                for (let i in this.paramData) {
                    let param = {
                        modelId: this.$storeSave.state.addelevanceObj.menuId,
                        paramName: '${' + this.paramData[i].param + '}',
                        paramType: this.paramData[i].type,
                        defaultVal: this.paramData[i].input
                    }
                    Conditions.tdpps.push(param)
                }
                let sql = this.formData.sql
                // for (let i in this.paramData){
                //     let param ={
                //         paramName: "${"+this.paramData[i].param+"}",
                //         paramType: this.paramData[i].type,
                //         defaultVal: this.paramData[i].input,
                //     };
                //     sql = this.formData.sql.replace(param.paramName,"'"+ param.defaultVal+ "'");; //sql语句
                // }
                Conditions['sql'] = sql
                ajax.post(QUERY_TMP_DATA_TABLE, Conditions).then(res => {
                    this.tableData = res.data.records
                    this.recordNumber = res.data.recordNumber
                }).catch(err => {
                    console.log('查询table数据失败')
                    console.log(err)
                })
            },
            getParams () {
                this.paramData = []
                let sqlList = this.formData.sql
                // 根据空格将字符串变成数组
                let sqls = sqlList.split(' ')
                // 匹配字符并且放入数组中
                for (let i in sqls) {
                    if (sqls[i].indexOf('${') != -1 && sqls[i].indexOf('}') != -1) {
                        let params = {
                            param: sqls[i].substring(2, sqls[i].length - 1)
                        }
                        this.paramData.push(params)
                    }
                }
                let arr1 = this.unique(this.paramData)
                this.paramData = arr1
            },
            // 数组去重
            unique (arr) {
                const res = new Map()
                return arr.filter((arr) => !res.has(arr.param) && res.set(arr.param, 1))
            },
            // 取消操作
            cancel () {
                this.$emit('showSelfData')
            },
            // 编辑返现数据
            editSqlData (val) {
                debugger
                this.editFlag = true
                this.editData = val
                let sqlInfo = {
                    optMode: '1',
                    pageNo: '1',
                    pageSize: '15',
                    modelId: val.menuId
                }
                ajax.post(GET_DATAINFO, sqlInfo).then(res => {
                    debugger
                    console.info(res)
                    this.tableData = res.data.page

                    // 将对应的数据库连接id放在这里
                    this.formData = {
                        connId: res.data.connId,
                        sql: res.data.pcWhere
                    }
                    let modelId = {
                        modelId: val.menuId
                    }
                    ajax.post(DATA_PARAM_QUERY, modelId).then(res => {
                        for (let i in res.data) {
                            let params = {
                                param: res.data[i].paramName.substring(2, res.data[i].paramName.length - 1),
                                type: res.data[i].paramType,
                                input: res.data[i].defaultVal
                            }
                            this.paramData.push(params)
                        }
                    })
                }).catch(err => {
                    console.log('查询table数据失败')
                    console.log(err)
                })
            }
        },
        mounted () {
            this.getDbLink()
        },
        components: {
            dataTableCom
        }
    }
</script>
<style lang="stylus" rel="stylesheet/stylus">
#getDataBySql
    .el-container
        .el-aside
        .el-main
            width 100%
            margin-top -10px

</style>
